package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jmp.autocofiguration.util.OssUtil2;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.dto.CardCustomerDto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.mapper.BusinessCardMapperExt;
import one.stand.mapper.BusinessCardPublicMapper;
import one.stand.mapper.SeeRecordPublicMapper;
import one.stand.mapper.UserTaskMapper;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.FollowRecordRequest;
import one.stand.response.BusinessCardResponse;
import one.stand.response.GetCompanyStaffResponse;
import one.stand.service.BusinessCardService;
import one.stand.service.CompanyBaseService;
import one.stand.service.FollowRecordService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class BusinessCardServiceImpl implements BusinessCardService {
    @Autowired
    private SeeRecordPublicMapper seeRecordPublicMapper;
    @Autowired
    private BusinessCardMapperExt businessCardMapperExt;
    @Autowired
    private BusinessCardPublicMapper businessCardPublicMapper;
    @Autowired
    private UserTaskMapper userTaskMapper;
    @Autowired
    private CompanyBaseService companyBaseService;

    /**
     * crm端查询名片列表
     *
     * @param request
     * @return
     */
    @Override
    public ResultModel<List<BusinessCardResponse>> selectBusinessCardList(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }

        return null;
    }

    @Override
    public ResultModel<Boolean> updateCardWelcomeSpeech(BusinessCardRequest request) {
        log.info("修改用户名片欢迎语:{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCard model = new BusinessCard();
        model.setCardId(request.getMyCardId());
        model.setWelcomeSpeech(request.getWelcomeSpeech());
        model.setShareSpeech(request.getShareSpeech());
        businessCardMapperExt.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Map<String, Object>> getCompanyStaffList(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        model.setCompanyId(request.getCId().intValue());
        model.setName(request.getName());
        List<GetCompanyStaffResponse> responseList = businessCardPublicMapper.getCompanyStaffList(model);

        Company company = companyBaseService.getById(request.getCId().intValue());
        PageResponse2<GetCompanyStaffResponse> pageInfo = ConvertUtils.page2(responseList, stff -> {
            UserTaskModel userTaskModel = userTaskMapper.selectNow(stff.getCardId().intValue());
            if (Objects.nonNull(userTaskModel)) {
                stff.setTargetAmount(Long.valueOf(userTaskModel.getTargetAmount()));
                stff.setCustomerNum(Long.valueOf(userTaskModel.getCustomerNum()));
            }
            stff.setCompanyLogo(company.getCompanyLogo());
            stff.setCompanyName(company.getCompanyName());
            stff.setVisitUser(seeRecordPublicMapper.selectVisitUser(stff.getCardId()));
            stff.setVisitNum(seeRecordPublicMapper.selectVisitNum(stff.getCardId()));
            return stff;
        });

        Map<String, Object> map = new HashMap<>(2);
        map.put("list", pageInfo.getList());
        map.put("totalNumber", pageInfo.getTotal());// 人数
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<GetCompanyStaffResponse> getCompanyStaffInfo(BusinessCardRequest request) {
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        model.setCardId(request.getCardId());
        List<GetCompanyStaffResponse> responseList = businessCardPublicMapper.getCompanyStaffList(model);
        AssertUtil.nonNull(responseList, ResultEnum.NO_DATA);

        Company company = companyBaseService.getById(request.getCId().intValue());
        GetCompanyStaffResponse stff = responseList.get(0);
        UserTaskModel userTaskModel = userTaskMapper.selectNow(stff.getCardId().intValue());
        if (Objects.nonNull(userTaskModel)) {
            stff.setTargetAmount(Long.valueOf(userTaskModel.getTargetAmount()));
            stff.setCustomerNum(Long.valueOf(userTaskModel.getCustomerNum()));
        }
        stff.setCompanyLogo(company.getCompanyLogo());
        stff.setCompanyName(company.getCompanyName());
        stff.setVisitUser(seeRecordPublicMapper.selectVisitUser(stff.getCardId()));
        stff.setVisitNum(seeRecordPublicMapper.selectVisitNum(stff.getCardId()));
        return ResultModel.success(stff);
    }

    @Override
    public ResultModel<Integer> manualAdd(BusinessCardRequest request) {

        if (StringUtils.isEmpty(request.getPhone()) && StringUtils.isEmpty(request.getPersonalWx())) {
            return ResultModel.fail("请输入手机号码~!");
        }
        BusinessCard cardModel = new BusinessCard();
        BeanUtils.copyProperties(request, cardModel);
        cardModel.setCreateTime(DateUtil.currentDate());
        cardModel.setType(2);
        cardModel.setStyle(1);
        cardModel.setCompanyKey(null);
        formatOss(cardModel);
        if (businessCardMapperExt.insertSelective(cardModel) > 0) {
            return ResultModel.success(cardModel.getCardId());
        }
        return ResultModel.fail();
    }

    private void formatOss(BusinessCard card) {
        card.setLogo(OssUtil2.getWebsiteUrlReplace(card.getLogo()));
        card.setPhoto(OssUtil2.getWebsiteUrlReplace(card.getPhoto()));
        card.setWxTwoCode(OssUtil2.getWebsiteUrlReplace(card.getWxTwoCode()));
        card.setWxCode(OssUtil2.getWebsiteUrlReplace(card.getWxCode()));
    }

    @Autowired
    private FollowRecordService followRecordService;

    @Override
    public ResultModel updAdd(BusinessCardRequest request) {
        CardCustomerDto model = businessCardPublicMapper.selectCustomer(request.getCardId());
        AssertUtil.nonNull(model, ResultEnum.FAIL);
        // 电话不同就添加跟进记录
        log.info("修改客户：电话号码由[{}]变成[{}]", model.getPhone(), request.getPhone());
        if (!(model.getPhone() + "").equals(request.getPhone() + "")) {
            JSONObject jsonObject = new JSONObject();
            StringBuffer data = new StringBuffer("电话号码由[");
            data.append(StringUtils.isBlank(model.getPhone()) ? "空" : model.getPhone());
            data.append("]变为[");
            data.append(StringUtils.isBlank(request.getPhone()) ? "空" : request.getPhone());
            data.append("]");
            jsonObject.put("data", data);
            jsonObject.put("type", 5);
            FollowRecordRequest recordRequest = new FollowRecordRequest();
            recordRequest.setCardId(request.getCardId());
            recordRequest.setId(request.getId());
            recordRequest.setFollowRemark(jsonObject.toJSONString());
            recordRequest.setMyCardId(request.getMyCardId());
            recordRequest.setFollowType(6);
            followRecordService.addFollow(recordRequest);
        }
        BusinessCard cardModel = new BusinessCard();
        BeanUtils.copyProperties(request, cardModel);
        cardModel.setCompanyKey(null);
        formatOss(cardModel);
        if (businessCardMapperExt.updateByPrimaryKeySelective(cardModel) > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();

    }

}
